/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package config;

import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.*;
import share.PGHelper;

/**
 *
 * @author Salm
 */
public class CFPrizePools extends JSONMapArray<CFPrizePools.Pool> {
    CFPrizePools()
    {
        this(makeRandomizer());
    }

    public CFPrizePools(SecureRandom randomizer) {
        this.randomizer = randomizer;
    }
    
    private final SecureRandom randomizer;

    @Override
    protected Pool newElement(Map<String, Object> elemJSON) {
        return new Pool(this.randomizer);
    }
    
    public static class Pool implements JSONable
    {
        Pool()
        {
            this(makeRandomizer());
        }

        Pool(SecureRandom randomizer) {
            this.randomizer = randomizer;
        }
        
        private final SecureRandom randomizer;
        
        private int totalPrizeRate = 0;
        private final NavigableMap<Integer, Integer> prizeIndices = new TreeMap();
        private final Map<Integer, CFPrize> prizes = new HashMap();

        @Override
        public void deser(Map<String, Object> json) {
            if (json.containsKey("prizes"))
            {
                json = (Map) json.get("prizes");
            }
            for (Map.Entry<String, Object> pzEntry : json.entrySet()) {
                int index = PGHelper.toInt(pzEntry.getKey());
                Map<String, Object> prizeJSON = (Map) pzEntry.getValue();
                
                int rate = PGHelper.toInt(prizeJSON.get("rate"));
                prizeIndices.put(totalPrizeRate, index);
                totalPrizeRate += rate;
                
                CFPrize prize = new CFPrize();
                prize.deser(prizeJSON);
                prizes.put(index, prize);
            }
        }
        
        public int randomPrize()
        {
            int randVal = randomizer.nextInt(totalPrizeRate);
            return prizeIndices.get(prizeIndices.floorKey(randVal));
        }
        
        public CFPrize getPrize(int index)
        {
            return prizes.get(index);
        }
    }
    
    public List<Integer> randomPrizes()
    {
        List<Integer> prizeIndices = new ArrayList(this.size());

        for (int i = 0; i < this.size(); ++i)
        {
            prizeIndices.add(this.get(i).randomPrize());
        }

        return prizeIndices;
    }
    
    public CFPrize getPrize(int pool, int index)
    {
        return this.get(pool).getPrize(index);
    }
    
    public static SecureRandom makeRandomizer()
    {
        return new SecureRandom(ByteBuffer.allocate(8)
                .putLong(System.currentTimeMillis()).array());
    }
}
